// components/search/module/sDate/sDate.js
const dayjs = require("dayjs");
Component({
  options: {
    styleIsolation: "apply-shared",
  },
  /**
   * 组件的属性列表
   */
  properties: {
    show: {
      type: Boolean,
      value: false,
    },
    data: {
      type: Object,
      value: () => {
        return {};
      },
    },
    time: {
      type: null,
      value: "",
    },
    start: {
      type: null,
      value: "",
    },
    end: {
      type: null,
      value: "",
    },
  },
  observers: {
    time(v) {
      this.setData({
        actDate: v,
      });
    },
    start(v) {
      let custom = this.data.custom;
      custom[0] = v;
      this.setData({
        custom,
      });
    },
    end(v) {
      let custom = this.data.custom;
      custom[1] = v;
      this.setData({
        custom,
      });
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    actDate: -1,
    custom: [],

    showDate: false,
    currentDate: null,
    title: "",
    type: 0,
    formatterDate: (e, v) => {
      return v + (e === "day" ? "日" : e === "month" ? "月" : "年");
    },
  },
  attached() {},
  /**
   * 组件的方法列表
   */
  methods: {
    onClose() {
      this.triggerEvent("close");
    },
    onCloseDate() {
      this.setData({
        showDate: false,
      });
    },
    dateChonge(e) {
      this.setData({
        actDate: e.currentTarget.dataset.id,
        custom: [],
      });
    },
    getDateVal(e) {
      this.setData({
        currentDate: e.detail,
      });
    },
    getDate() {
      let { type, currentDate, custom } = this.data;
      custom[type] = dayjs(currentDate).format("YYYY-MM-DD");
      this.setData({
        custom,
        showDate: false,
      });
    },
    openDate(e) {
      let type = e.currentTarget.dataset.type;
      let date = +dayjs(this.data.custom[type] || dayjs().startOf("day"));
      this.setData({
        actDate: "custom",
        title: type == 0 ? "开始时间" : "结束时间",
        showDate: true,
        currentDate: date,
        type,
      });
    },
    getValue() {
      let { actDate, data, custom } = this.data;
      custom = JSON.parse(JSON.stringify(custom));
      this.triggerEvent("value", {
        type: data.names[0],
        value: actDate,
      });
      if (actDate === "custom") {
        if (custom[0] || custom[1]) {
          this.triggerEvent("value", {
            type: data.names[1],
            value: custom[0] || custom[1],
          });
          this.triggerEvent("value", {
            type: data.names[2],
            value: custom[1] || custom[0],
          });
        }
      }
      this.onClose();
    },
  },
});
